<?php
// +----------------------------------------------------------------------
// | quickadmin框架 [ quickadmin框架 ]
// +----------------------------------------------------------------------
// | 版权所有 2020~2022 南京新思汇网络科技有限公司
// +----------------------------------------------------------------------
// | 官方网站: https://www.quickadmin.top
// +----------------------------------------------------------------------
// | Author: zs <909883663@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\Site;
use app\BaseController;
use app\dic\DicOrder;
use app\dic\DicProduct;
use app\dic\DicPublic;
use app\dic\DicSite;
use app\dic\OrderDic;
use think\App;
use think\facade\Db;
use util\Excel;
use think\cache\driver\Redis;

use util\Token;
/*
 * @Description: index
 * @Date: 2021-05-25 14:57:43
 */

class Index extends BaseController
{

    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new Site();
    }


    // 首页

    public function index()
    {

        // halt(phpinfo());
        //mock数据


        $data = [
            'a' => ['c' => 1, 'b' => 2],
            'b1' => 2,
            'c1' => 2,
            'd1' => 2,
            'e1' => 2,
            'f1' => 2,
            'h1' => 2,
            'i1' => 2,
            'j1' => 2,
            'k1' => 2,
            'l1' => 2,
            'm1' => 2,
            'n1' => 2,
            'o1' => 2,
            'p1' => 2,
            'q1' => 2,
            'r1' => 2,
            's1' => 2,
            't1' => 2,
            'u1' => 2,
            'v1' => 2,
            'w1' => 2,
            'x1' => 2,
            'y1' => 2,
            'z1' => 2,

        ];

        $res = mgtable('ceshi')->insert($data);
        halt($res);
        return json($data);
    }



    /**
     * 店铺数据迁移
     */
    public function sitetransfer()
    {
        //迁移shopify店铺
        $rst =  table('fedition_accounturl')->where(['info' => 'shopify'])->select()->toarray();
        foreach ($rst as $v) {
            $rst_new[] = [
                'site_name' => $v['name'],
                'site_url' => $v['shopifyname'],
                'site_type' => DicSite::$site_type_1,
                'status' => $v['status'],
                'currency' => $v['currency'],
                'apikey' => $v['shopifyapikey'],
                'apisecret' => $v['shopifysecretapikey'],
                'add_time' => date('Y-m-d H:i:s', $v['createtime']),
                'update_time' => date('Y-m-d H:i:s', $v['updatetime']),
                'adminid' => 1
            ];
        }
        table('site')->insertAll($rst_new);
        return '数据转入成功';
    }


    /**
     * 通过商品id获取单个产品信息
     */

    public function  get_product_product_id()
    {
        $site_id = input('site_id');
        $product_id = input('product_id');
        $site = table('site')->where(['id' => $site_id])->find();
        $url = $site['site_url'] . DicProduct::$product_url . '/' . $product_id . '.json';
        //取出单个商品
        $product = geturl($url, $site['apikey'], $site['apisecret']);
        $product = json_decode($product, true);
        halt($product);
        $product = $product['product'];
        halt($product);
    }



    // 搬数据
    public function ban()
    {
        $data = Excel::import('storage/bra10.xls');
        unset($data[1], $data[2]);
        foreach ($data as  $value) {
            table('sumskucount')->where(['sku' => strtolower($value[0])])->update(['sum' => $value[3]]);
        }
        return success('更新成功');
    }


    /**
     * 通过商品id获取元字段信息
     */

    public function  get_metafield_product_id()
    {
        // $str = 'bra' . DicPublic::$encryption_str;
        // halt(explode(DicPublic::$encryption_str, $str));
        $site_id = input('site_id');
        $product_id = input('product_id');
        $site = table('site')->where(['id' => $site_id])->find();
        $url = $site['site_url'] . DicProduct::$product_url . '/' . $product_id . '/metafields.json';
        $metafield = geturl($url, $site['apikey'], $site['apisecret']);
        $metafield = json_decode($metafield, true);
        // halt($metafield['metafields']);
        if (isset($metafield['metafields'])) {
            halt(array_column($metafield['metafields'], 'value', 'key'));
        }
        return [];
    }

    //生成sku
    public function get_sku()
    {
        $product_id =  input('product_id') ? input('product_id') : 7969504854235;
        $brand = table('brand')->where(['product_id' => $product_id])->find();
        if (!isset($brand['title'])) {
            $brand['title'] = '';
        }
        $color = table('color')->field('id,title')->select()->toarray();
        $color = array_column($color, 'title');
        asort($color);
        $color = array_values($color);
        $size = table('size')->field('title')->select()->toarray();
        $size =  array_column($size, 'title');
        asort($size);
        $size_info = array_values($size);
        $cup = table('cup')->field('title')->select()->toarray();
        $cup =  array_column($cup, 'title');
        asort($cup);
        $cup_info = array_values($cup);
        $excel = table('demo_excel')->field('id,title')->select()->toarray();
        $sku_table = table('sku_table')->where(['product_id' => $product_id])->find();
        $colors = '';
        $sizecup = '';
        $quantity = '';
        $table_cup = '';
        $table_size = '';
        $switch = 0;
        $remove_sku = array();
        if (!empty($sku_table)) {
            if ($sku_table['color']) {
                $colors = json_decode($sku_table['color']);
            }
            if ($sku_table['cup']) {
                $table_cup = json_decode($sku_table['cup']);
            }
            if ($sku_table['size']) {
                $table_size = json_decode($sku_table['size']);
            }
            if ($sku_table['excel']) {
                $sizecup = (int)$sku_table['excel'];
            }
            if ($sku_table['quantity']) {
                $quantity = (int)$sku_table['quantity'];
            }
            if ($sku_table['switch']) {
                $switch = (int)$sku_table['switch'];
            }
            if ($sku_table['sku']) {
                $sku_table['sku'] = json_decode($sku_table['sku']);
            }
            if ($sku_table['sku_name']) {
                $sku_table['sku_name'] = json_decode($sku_table['sku_name']);
            }
            if ($sku_table['option1']) {
                $sku_table['option1'] = json_decode($sku_table['option1']);
            }
            if ($sku_table['option2']) {
                $sku_table['option2'] = json_decode($sku_table['option2']);
            }
            if ($sku_table['option3']) {
                $sku_table['option3'] = json_decode($sku_table['option3']);
            }

            if ($sku_table['remove_sku']) {
                $sku_table['remove_sku'] = json_decode($sku_table['remove_sku']);
                for ($i = 0; $i < count($sku_table['remove_sku']); $i++) {
                    $remove_sku[$i]['name'] = $sku_table['remove_sku'][$i];
                }
            }
            $sku_table['tableData'] = array();
            if (!empty($sku_table['sku']) && !empty($sku_table['sku_name'])) {
                for ($i = 0; $i < count($sku_table['sku']); $i++) {
                    $sku_table['tableData'][$i]['sku'] = $sku_table['sku'][$i] ? $sku_table['sku'][$i] : '';
                    $sku_table['tableData'][$i]['name'] = $sku_table['sku_name'][$i] ? $sku_table['sku_name'][$i] : '';
                    $sku_table['tableData'][$i]['option1'] = $sku_table['option1'][$i] ? $sku_table['option1'][$i] : '';
                    $sku_table['tableData'][$i]['option2'] = $sku_table['option2'][$i] ? $sku_table['option2'][$i] : '';
                    $sku_table['tableData'][$i]['option3'] = $sku_table['option3'][$i] ? $sku_table['option3'][$i] : '';
                }
            }
        }
        $arr = [
            'brand_title' => $brand['title'],

            'color' =>  $color,
            'colors' => $colors,
            'size' => $table_size,
            'sizes' => $size_info,
            'cup' => $table_cup,
            'cups' => $cup_info,

            'product_id' => $product_id,
            'excel' => $excel,
            'sku_table' => $sku_table,
            'sizecup' => $sizecup,
            'quantity' => $quantity,
            'switch' => $switch,
            'remove_sku' => $remove_sku,
        ];
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $arr,
        ];
        return json($data);
    }

    //尺码映射
    public function get_excel()
    {
        $option1 = input('option1');
        $option1 = json_decode($option1, true);
        $option2 = input('option2');
        $option2 = json_decode($option2, true);
        $option3 = input('option3');
        $option3 = json_decode($option3, true);
        $sku_name = input('sku_name');
        $sku_name = json_decode($sku_name, true);

        $sku_data = input('sku_data');
        $sku_data = json_decode($sku_data, true);;
        $excel_id = input('excel_id') ? input('excel_id') : 0;
        $brand = input('brand') ? input('brand') : 1;
        $quantity = input('quantity') ? input('quantity') : 1;
        $excel_data = table('demo_excel')->where(['id' => $excel_id])->find();
        $new = [];
        $skudata = [];
        if (!empty($excel_data)) {
            foreach ($sku_data as $value) {
                if ($this->excel_transfer($brand, $value, $excel_data['attachfile']) == 'error') {
                    return error('当前模板没有对应尺码' . $value);
                };
                $new[] = $this->excel_transfer($brand, $value, $excel_data['attachfile']);
            }
        } else {
            foreach ($sku_data as $value) {
                $new[] = $this->excel_transfer($brand, $value, '', 2);
            }
        }
        $new_array = array();
        if (!empty($new)) {
            foreach ($new as $k => $v) {
                $skudata[$k]['name'] = $sku_name[$k] ? $sku_name[$k] : '';
                if (strstr($v, '+')) {
                    $skudata[$k]['sku'] = $v;
                    $new_array[] = $v;
                } else {
                    if ($quantity > 1) {
                        $skudata[$k]['sku'] = $v . '-' . $quantity;
                        $new_array[] = $v . '-' . $quantity;
                    } else {
                        $skudata[$k]['sku'] = $v;
                        $new_array[] = $v;
                    }
                }
                $skudata[$k]['option1'] = $option1[$k] ? $option1[$k] : '';
                $skudata[$k]['option2'] = $option2[$k] ? $option2[$k] : '';
                $skudata[$k]['option3'] = $option3[$k] ? $option3[$k] : '';
            }
        }
        $news['skudata'] = $skudata;
        $news['new'] = $new_array;
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $news,
        ];
        return json($data);
    }
    //excel 数据转换
    public function excel_transfer($brand = '', $value = 'Blue-38A', $attachfile = 'http://api.fan-zhoubuy.com/storage/system/20230414/5082ab88b750b00432c7fa96c2b3c76b.xls', $type = 1)
    {
        //切割颜色取出对应的值
        $explode_arr = explode('-', $value);
        if ($type == 2) {
            return strtolower($brand) . '-' . $explode_arr[0] . '-' . $explode_arr[1];
        } else {
            $excel_data = excel_data(excel_url($attachfile));
            if (!isset($excel_data[$explode_arr[1]])) {
                return 'error';
            }
            return strtolower($brand) . '-' . $explode_arr[0] . '-' . $excel_data[$explode_arr[1]];
        }
    }


    public function sku_table_deal()
    {
        $post = $this->request->post();
        $sku_table = table('sku_table')->where(['product_id' => $post['product_id']])->find();
        if ($sku_table) {
            table('sku_table')->where(['product_id' => $sku_table['product_id']])->update($post);
            table('product')->where(['id' => $sku_table['product_id']])->update(['table_status' => DicProduct::$table_status_1]);
            return success('更新成功');
        } else {
            table('sku_table')->insert($post);
            table('product')->where(['id' => $post['product_id']])->update(['table_status' => DicProduct::$table_status_1]);
            return success('新增成功');
        }
    }

    /**
     * SKU排行
     * @param array params
     */
    public function sku_ranking()
    {
        $post = $this->request->post();
        $sku_name = $post['start_time'] ? $post['start_time'] : 'bra01';
        $start_time = $post['start_time'] ? strtotime($post['start_time']) : mktime(0, 0, 0, date('m'), 1, date('Y'));
        $end_time =  time();
        $sql = "SELECT 
        c.sku,
        sum(b.quantity) as count,
        b.title,
        e.handle_url,
        b.product_id,
        c.variants_id as SKUid
        FROM qu_order as a
        LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
        LEFT JOIN qu_order_sku as c ON b.variant_id=c.variants_id
        LEFT JOIN qu_order_product as e ON b.product_id=e.product_id
        where a.financial_status = 'paid'
        AND a.created_at >= " . $start_time . "
        AND a.created_at <= " . $end_time . "
        AND c.id > 1
        AND b.sku like '%{$sku_name}%'
        GROUP BY SKUid
        ORDER BY count DESC
    ";
        $join_datas = Db::query($sql);

        if (!$join_datas) {
            return [];
        }

        // halt($this->model->getlastsql());
        // halt(getsku());
        $colors = ['beige', 'black', 'blue', 'pink', 'skin', 'grey'];
        $sizes = ['m', 'l', 'xl', '2xl', '3xl', '4xl', '5xl', '6xl', '7xl', '36', '38', '40', '42', '44', '46'];
        $merge_sku[$sku_name] = 0;
        foreach ($colors as  $color) {
            $merge_sku[$sku_name . '_' . $color] = 0;
            foreach ($sizes as $size) {
                $merge_sku[$sku_name . '_' . $color . '_' . $size] = 0;
            }
        }
        //bra01-black+blue-xl-2
        foreach ($join_datas as $join_data) {
            //数量
            $multiple = 1;
            $sku_title_arr =  explode('-', strtolower($join_data['sku']));
            file_put_contents('testsku.txt', $join_data['sku']);
            if (isset($sku_title_arr[0])) {
                if (isset($sku_title_arr[1])) {
                    if (isset($sku_title_arr[3])) {
                        $multiple = $sku_title_arr[3];
                    }
                    $sku_title_arr1 =  explode('+', $sku_title_arr[1]);
                    foreach ($sku_title_arr1 as $vl) {
                        $merge_sku[$sku_title_arr[0]] = $merge_sku[$sku_title_arr[0]] + ((int)$join_data['count']) * $multiple;
                        $merge_sku[$sku_title_arr[0] . '_' . $vl] = $merge_sku[$sku_title_arr[0] . '_' . $vl] + ((int)$join_data['count']) * $multiple;
                        if (isset($sku_title_arr[2])) {
                            $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]] = $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]]  + ((int)$join_data['count']) * $multiple;
                        }
                    }
                }
            }
        }
        foreach ($merge_sku as $k => $v) {
            if ($v == 0) {
                unset($merge_sku[$k]);
            }
        }
        $merge_sku_new = array();
        foreach ($merge_sku as $k => $v) {
            $merge_sku_new[] =
                ['sku' => $k, 'count' => $v];
        }
        // halt($merge_sku_new);
        $header = [['sku', 'sku'], ['count', 'count']];
        $fileName = $sku_name;
        return Excel::exportData($merge_sku_new, $header, $fileName, 'xlsx');
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => count($merge_sku_new),
            'data' => $merge_sku_new,
        ];
        return json($data);
    }


    //通过excel_id找excel对应数据
    public function get_excel_data()
    {
        $excel_id = input('excel_id') ? input('excel_id') : 1;
        $excel = table('demo_excel')->field('attachfile')->where(['id' => $excel_id])->find();
        $excel_data = excel_data(excel_url($excel['attachfile']));
        foreach ($excel_data as $key => $value) {
            $arr[] = ['cup' => $key, 'title' => $value];
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $arr,
        ];
        return json($data);
    }

    //首页判断运营权限
    public function judgment_authority()
    {
        $token = $this->request->header('token');
        $admin = Token::admin($token);
        if(!empty($admin)){
            $group_admin = table('system_group_admin')
            // ->where('group_id', 5)
            ->where('admin_id', $admin['id'])
            ->find();
            if(!empty($group_admin)){
                if($group_admin['group_id'] == 5){
                    return 5;
                }
                if($group_admin['group_id'] == 1){
                    return 1;
                }
            }
        }
        return 2;
    }
    //首页统计运营数据
    public function dashboard_new()
    {
        $post = $this->request->post();
        if(empty($post)){
            $post['day_changes'] = 0;
            $post['start_time'] = time() - 15 * 3600;
            $post['end_time'] = time() + 9 * 3600;
        }
        
        //时区开始
        $start_time = $post['start_time'];
        $end_time = $post['end_time'];
        $start_time2 = $post['start_time'] + 9 * 3600;
        $end_time2 = $post['end_time'] + 9 * 3600;
        //时区1
        $start_time = strtotime(date('Y-m-d 00:00:00', $start_time));
        if ($post['day_changes'] == 3) {
            $start_time = strtotime(date('Y-m-1 00:00:00', $start_time));
        }
        if ($post['day_changes'] == 101) {
            $end_time = strtotime(date('Y-m-d 23:59:59', $end_time));
        } else {
            $end_time = strtotime(date('Y-m-d 00:00:00', $end_time));
        }
        //时区2
        $start_time2 = strtotime(date('Y-m-d 00:00:00', $start_time2));
        if ($post['day_changes'] == 3) {
            $start_time2 = strtotime(date('Y-m-1 00:00:00', $start_time2));
        }
        if ($post['day_changes'] == 101) {
            $end_time2 = strtotime(date('Y-m-d 23:59:59', $end_time2));
        } else {
            $end_time2 = strtotime(date('Y-m-d 00:00:00', $end_time2));
        }
        //时区结束

        $redis = new Redis();
        $dashboards = $redis->get('dashboard-new-' . $start_time . '-' . $end_time . '-' . $post['day_changes']);
        if (!empty($dashboards)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $dashboards,
            ];
            return json($data);
        }

        $exchange = $redis->get('exchangerate');
        if(empty($exchange)){
            $exchange = table('exchange')
                ->where('currency','USD')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate', $exchange, 60 * 60 * 24 );
        }
        $exchange_eur = $redis->get('exchangerate_eur');
        if(empty($exchange_eur)){
            $exchange_eur = table('exchange')
                ->where('currency','EUR')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate_eur', $exchange_eur, 60 * 60 * 24 );
        }
        //站点
        // $integration = $redis->get('integration');
        // if(empty($integration)){
        //     $site_arr = table('site')
        //         ->field('id,site_name,international_sites')
        //         ->where('status','normal')
        //         ->select()->toarray();
        //     $site_total_new = array();
        //     $site_total_new2 = array();
        //     $integration = array();
        //     foreach ($site_arr as $k=>$v) {
        //         $site_total_new[$v['id']] = $v['site_name'];
        //         $site_total_new2[$v['id']] = $v['international_sites'];
        //     }
        //     $integration['site_total_new'] = $site_total_new;
        //     $integration['site_total_new2'] = $site_total_new2;
        //     $redis->set('integration', $integration, 60 * 60 * 24 );
        // }else{
        //     $site_total_new = $integration['site_total_new'];
        //     $site_total_new2 = $integration['site_total_new2'];
        // }
        //站点

        //arr
        $arr = array();
        $arr['paid'] = 0;
        $arr['sales'] = 0;
        $arr['dispute'] = 0;
        $arr['refund_money'] = 0;
        $arr['sales_usd'] = 0;
        $arr['sales_eur'] = 0;
        $arr['estimated_cost'] = 0;
        $arr['gross_profit'] = 0;
        $arr['logistics'] = 0;
        $arr['roi'] = 0;
        $arr['purchase'] = 0;
        $arr['adv_cost'] = 0;
        $arr['platform_discount'] = 0;

        //
        //店铺业绩
        $where1 = array();
        $where1[]  = ['a.created_at', '>=', $start_time];
        $where1[]  = ['a.created_at', '<=', $end_time];

        $where2 = array();
        $where2[]  = ['a.created_at', '>=', $start_time2];
        $where2[]  = ['a.created_at', '<=', $end_time2];    

        $where_total_price[] = ['a.financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid]];
        $shopify_sales_arr = array();

        $shopify_sales1 = table('order')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->field('a.site_id,sum(total_price) as total,sum(countnum) as count,a.currency,sum(freight) as freight,sum(material) as material,b.international_sites,b.site_name')
            ->where($where1)
            ->where($where_total_price)
            ->where('international_sites','美国站')
            ->group('site_id')
            ->order('total desc')
            ->select()->toarray();
        if(!empty($shopify_sales1)){
            foreach ($shopify_sales1 as $k=>$v) {
                // unset($site_total_new[$v['site_id']]);
                $wheregroup = array();
                $wheregroup[]  = ['a.updatetime', '>=', $end_time];
                $wheregroup['a.site_id'] = $v['site_id'];
                $wheregroup['a.type'] = '主运营';
                $site_log = table('site_log')
                    ->field("b.nickname")
                    ->alias('a')
                    ->join('qu_system_admin b', 'b.id = a.admin_id', 'left')
                    ->where($wheregroup)
                    ->find();
                if(!isset($site_log['nickname']) || empty($site_log['nickname'])){
                    $site_log['nickname'] = '';
                }
                
                $zsales = (float)number_format($v['total'], 3, '.', '');
                $shopify_sales_remarks = '';
                if($v['currency'] == 'EUR'){
                    $shopify_sales_remarks = '原销售额为€'.$zsales;
                    $zsales = (float)number_format((float)$zsales * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }
                //广告
                $start_time_str = date('Y-m-d H:i:s', $start_time);
                $end_time_str =  date('Y-m-d H:i:s', $end_time);
                $adv_where = array();
                $adv_where[]  = ['create_time', '>=', $start_time_str];
                $adv_where[]  = ['create_time', '<', $end_time_str];
                $zadvcost_z = array();
                $advplat_arr = table('advplat')
                    ->where('site_id',$v['site_id'])
                    ->select()->toarray();
                $zadvcost_new = 0;
                if(!empty($advplat_arr)){
                    foreach ($advplat_arr as $k0=>$v0) {
                        $zadvcost_z = table('advertising')
                            ->where($adv_where)
                            ->where('plat_account',$v0['id'])
                            ->where('status','normal')
                            ->select()->toarray();
                            if(!empty($zadvcost_z)){
                                foreach ($zadvcost_z as $k1=>$v1) {
                                    $zadvcost_new = (float)number_format((float)$zadvcost_new + (float)$v1['cost'], 3, '.', '');
                                }
                            }
                    }
                }
                //广告结束
                //时间段退款
                $where_refund = array();
                $where_refund[]  = ['processed_at', '>=', $start_time];
                $where_refund[]  = ['processed_at', '<=', $end_time];
                $where_refund[]  = ['refund_status', '<=', 'success'];
                $sales_refund = table('order_refunds')
                    ->where($where_refund)
                    ->where(['site_id' => $v['site_id']])
                    ->sum('amount');
                $sales_refund = (float)number_format($sales_refund, 3, '.', '');

                $v['freight'] = (float)number_format((float)$v['freight'] / (float)$exchange['proportion'], 3, '.', '');
                $v['material'] = (float)number_format((float)$v['material'] / (float)$exchange['proportion'], 3, '.', '');
                $gross_profit = (float)number_format((float)$zsales*0.94 - (float)$v['freight'] - (float)$v['material'] - $zadvcost_new, 3, '.', '');
                if ($zsales > 0.02 && $zadvcost_new > 0.02) {
                    $roi = (float)number_format((float)$zsales / (float)$zadvcost_new, 3, '.', '');
                }else{
                    $roi = 0;
                }
                $arr['sales'] = (float)number_format($zsales + $arr['sales'], 3, '.', '');
                $arr['logistics'] = (float)number_format($v['freight'] + $arr['logistics'], 3, '.', '');
                $arr['purchase'] = (float)number_format($v['material'] + $arr['purchase'], 3, '.', '');
                $arr['adv_cost'] = (float)number_format($zadvcost_new + $arr['adv_cost'], 3, '.', '');
                $arr['sales_usd'] = (float)number_format($zsales + $arr['sales_usd'], 3, '.', '');
                $arr['paid'] = (float)number_format($v['count'] + $arr['paid'], 3, '.', '');
                $arr['refund_money'] = (float)number_format($sales_refund + $arr['refund_money'], 3, '.', '');
                $shopify_sales_arr[] = [
                    'id' => $v['site_id'],
                    'name' => $v['site_name'],
                    'gross_profit' => $gross_profit,
                    'count' => (int)$v['count'],
                    'sales' => $zsales,
                    'refund' => $sales_refund,
                    'nickname' => $site_log['nickname'],
                    'zadvcost_new' => $zadvcost_new,
                    'roi' => $roi,
                    'remarks' => $shopify_sales_remarks,
                ];
            }
        }
        $shopify_sales2 = table('order')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->field('a.site_id,sum(total_price) as total,sum(countnum) as count,a.currency,sum(freight) as freight,sum(material) as material,b.international_sites,b.site_name')
            ->where($where2)
            ->where($where_total_price)
            ->where('international_sites','欧洲站')
            ->group('site_id')
            ->order('total desc')
            ->select()->toarray();
        if(!empty($shopify_sales2)){
            foreach ($shopify_sales2 as $k=>$v) {
                // unset($site_total_new[$v['site_id']]);
                $wheregroup = array();
                $wheregroup[]  = ['a.updatetime', '>=', $end_time2];
                $wheregroup['a.site_id'] = $v['site_id'];
                $wheregroup['a.type'] = '主运营';
                $site_log = table('site_log')
                    ->field("b.nickname")
                    ->alias('a')
                    ->join('qu_system_admin b', 'b.id = a.admin_id', 'left')
                    ->where($wheregroup)
                    ->find();
                if(!isset($site_log['nickname']) || empty($site_log['nickname'])){
                    $site_log['nickname'] = '';
                }
                
                $zsales = (float)number_format($v['total'], 3, '.', '');
                $shopify_sales_remarks = '';
                $old_sales = 0;
                if($v['currency'] == 'EUR'){
                    $old_sales = $zsales;
                    $shopify_sales_remarks = '原销售额为€'.$zsales;
                    $zsales = (float)number_format((float)$zsales * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }
                //广告
                $start_time_str2 = date('Y-m-d H:i:s', $start_time2);
                $end_time_str2 =  date('Y-m-d H:i:s', $end_time2);
                $adv_where = array();
                $adv_where[]  = ['create_time', '>=', $start_time_str2];
                $adv_where[]  = ['create_time', '<', $end_time_str2];
                $zadvcost_z = array();
                $advplat_arr = table('advplat')
                    ->where('site_id',$v['site_id'])
                    ->select()->toarray();
                $zadvcost_new = 0;
                if(!empty($advplat_arr)){
                    foreach ($advplat_arr as $k0=>$v0) {
                        $zadvcost_z = table('advertising')
                            ->where($adv_where)
                            ->where('plat_account',$v0['id'])
                            ->where('status','normal')
                            ->select()->toarray();
                            if(!empty($zadvcost_z)){
                                foreach ($zadvcost_z as $k1=>$v1) {
                                    $zadvcost_new = (float)number_format((float)$zadvcost_new + (float)$v1['cost'], 3, '.', '');
                                }
                            }
                    }
                }
                //广告结束
                //时间段退款
                $where_refund = array();
                $where_refund[]  = ['processed_at', '>=', $start_time2];
                $where_refund[]  = ['processed_at', '<=', $end_time2];
                $where_refund[]  = ['refund_status', '<=', 'success'];
                $sales_refund = table('order_refunds')
                    ->where($where_refund)
                    ->where(['site_id' => $v['site_id']])
                    ->sum('amount');
                $sales_refund = (float)number_format($sales_refund, 3, '.', '');

                $v['freight'] = (float)number_format((float)$v['freight'] / (float)$exchange['proportion'], 3, '.', '');
                $v['material'] = (float)number_format((float)$v['material'] / (float)$exchange['proportion'], 3, '.', '');
                $gross_profit = (float)number_format((float)$zsales*0.94 - (float)$v['freight'] - (float)$v['material'] - $zadvcost_new, 3, '.', '');
                if ($zsales > 0.02 && $zadvcost_new > 0.02) {
                    $roi = (float)number_format((float)$zsales / (float)$zadvcost_new, 3, '.', '');
                }else{
                    $roi = 0;
                }

                $arr['sales'] = (float)number_format($zsales + $arr['sales'], 3, '.', '');
                $arr['logistics'] = (float)number_format($v['freight'] + $arr['logistics'], 3, '.', '');
                $arr['purchase'] = (float)number_format($v['material'] + $arr['purchase'], 3, '.', '');
                $arr['adv_cost'] = (float)number_format($zadvcost_new + $arr['adv_cost'], 3, '.', '');
                $arr['sales_eur'] = (float)number_format($old_sales + $arr['sales_eur'], 3, '.', '');
                $arr['paid'] = (float)number_format($v['count'] + $arr['paid'], 3, '.', '');
                $arr['refund_money'] = (float)number_format($sales_refund + $arr['refund_money'], 3, '.', '');
                $shopify_sales_arr[] = [
                    'id' => $v['site_id'],
                    'name' => $v['site_name'],
                    'gross_profit' => $gross_profit,
                    'count' => (int)$v['count'],
                    'sales' => $zsales,
                    'refund' => $sales_refund,
                    'nickname' => $site_log['nickname'],
                    'zadvcost_new' => $zadvcost_new,
                    'roi' => $roi,
                    'remarks' => $shopify_sales_remarks,
                ];
            }
        }
        //店铺业绩结束

        // if(!empty($site_total_new)){
        //     foreach ($site_total_new as $kst => $vst) {
        //         if(isset($site_total_new2[$kst]) && !empty($site_total_new2[$kst])){
        //                 //时间段退款
        //         }
        //     }
        // }
        $arr['platform_discount'] = (float)number_format($arr['sales']*0.06, 3, '.', '');
        $arr['gross_profit_handle1'] = '销售额-物流-采购-广告-手续费(6%)';
        $arr['gross_profit_handle2'] = $arr['sales'].'-'.$arr['logistics'].'-'.$arr['purchase'].'-'.$arr['adv_cost'].'-'.$arr['platform_discount'];
        $arr['gross_profit'] = (float)number_format($arr['sales']*0.94 - (float)$arr['logistics'] - (float)$arr['purchase'] - (float)$arr['adv_cost'], 2, '.', '');
        $newarr = array();
        $newarr['arr'][] = $arr;
        $newarr['shopify_sales'] = $shopify_sales_arr;
        $redis->set('dashboard-new-' . $start_time . '-' . $end_time . '-' . $post['day_changes'], $newarr, 60*3);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $newarr,
        ];
        return json($data);
    }

     //首页统计运营数据
    public function dashboard_new_edit()
    {
        $id = input('id');
        $post_start_time = input('post_start_time');
        $post_end_time = input('post_end_time');
        $row['id'] = $id;
        $row['post_start_time'] = $post_start_time;
        $row['post_end_time'] = $post_end_time;
        if (empty($id) || empty($post_start_time) || empty($post_end_time)) {
            return error('参数错误,请稍后再试');
        }
        //运营业绩详情
        
        if ($this->request->isPost()) {
            $post = $this->request->post();
            return success('保存成功！');
        }
        return success('ok', $row);
    }
    //个人业绩
    public function dashboard_personal()
    {
        $post = $this->request->post();
        if(isset($post['admin_id']) && !empty($post['admin_id'])){
            $adv_where[] = ['admin_id', 'in', $post['admin_id']];
            $where_day[] = ['admin_id', 'in', $post['admin_id']];

            $post['admin_type'] = implode(',',$post['admin_id']); 
        }else{
            $post['admin_type'] = 0; 
        }
        $start_time = !empty($post['start_time']) ? $post['start_time'] : strtotime(date('Y-m-d 00:00:00', time() - 15 * 3600));
        $start_time = strtotime(date('Y-m-d 00:00:00', $start_time));
        if ($post['day_changes'] == 3) {
            $start_time = strtotime(date('Y-m-1 00:00:00', $start_time));
        }
        $start_time_str = date('Y-m-d H:i:s', $start_time);
        $end_time = !empty($post['end_time']) ? $post['end_time'] : strtotime(date('Y-m-d 00:00:00', time() + 9 * 3600));
        if ($post['day_changes'] == 101) {
            $end_time = strtotime(date('Y-m-d 23:59:59', $end_time));
        } else {
            $end_time = strtotime(date('Y-m-d 00:00:00', $end_time));
        }
        $end_time_str =  date('Y-m-d H:i:s', $end_time);
        $redis = new Redis();
        $dashboards = $redis->get('dashboard-personal-' . $start_time . '-' . $end_time . '-' . $post['day_changes'] . '-' . $post['admin_type']);
        if (!empty($dashboards)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $dashboards,
            ];
            return json($data);
        }

        $exchange = $redis->get('exchangerate');
        if(empty($exchange)){
            $exchange = table('exchange')
                ->where('currency','USD')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate', $exchange, 60 * 60 * 24 );
        }
        $exchange_eur = $redis->get('exchangerate_eur');
        if(empty($exchange_eur)){
            $exchange_eur = table('exchange')
                ->where('currency','EUR')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate_eur', $exchange_eur, 60 * 60 * 24 );
        }

        $adv_where[]  = ['create_time', '>=', $start_time_str];
        $adv_where[]  = ['create_time', '<', $end_time_str];

        $two_admin = array();
        //运营业绩
        $where_day[]  = ['time_stamp', '>=', $start_time];
        $where_day[]  = ['time_stamp', '<', $end_time];
        $shopify_sales_day = table('shopify_personreport_day')
            ->field('admin_id,sum(total_price) as total,sum(count) as counts,label,site_id,sum(freight) as freight,sum(material) as material')
            ->where($where_day)
            ->group('admin_id')
            ->order('total desc')
            ->select()
            ->toarray();
        if (!empty($shopify_sales_day)) {
            foreach ($shopify_sales_day as $key => $value) {
                $remarks = '';
                //货币转换
                if(isset($value['currency']) && $value['currency'] == 'EUR'){
                    $remarks = '原销售额为€'.$value['total'];
                    $value['total'] = (float)number_format((float)$value['total'] * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }

                $two_admin[] = $value['admin_id'];
                $system_admin = table('system_admin')->where(['id' => $value['admin_id']])->find();
                if (!empty($system_admin)) {
                    if($system_admin['status'] !== 1){
                        continue;
                    }
                    $admin_name = $system_admin['nickname'];
                } else {
                    $admin_name = '';
                }
                $where_admin['admin_id'] = $value['admin_id'];
                $zadvcost_z = table('advertising')
                    ->field('sum(cost) as cost')
                    ->where($adv_where)
                    ->where('status','normal')
                    ->where($where_admin)
                    ->find();
                if(!empty($zadvcost_z['cost'])){
                    $zadvcost = $zadvcost_z['cost'];
                }else{
                    $zadvcost = 0;
                }
                $zroi = 0;
                if ($zadvcost > 0.001 && $value['total'] > 0.001) {
                    $zroi = number_format((float)$value['total']*0.94 / (float)$zadvcost, 3, '.', '');
                } //转化率ROI
                $value['freight'] = (float)number_format((float)$value['freight'] / (float)$exchange['proportion'], 3, '.', '');
                $value['material'] = (float)number_format((float)$value['material'] / (float)$exchange['proportion'], 3, '.', '');
                //毛利计算新增规则
                $profit = (float)number_format((float)$value['total']*0.94 - (float)$value['freight'] - (float)$value['material'] - (float)$zadvcost, 3, '.', '');
                // remarks
                $wheregroup[]  = ['a.updatetime', '>=', $end_time];
                $wheregroup['a.admin_id'] = $value['admin_id'];
                $site_log = table('site_log')
                    ->field("a.*,b.site_name")
                    ->alias('a')
                    ->join('qu_site b', 'b.id = a.site_id', 'left')
                    ->where($wheregroup)
                    ->select()->toarray();
                foreach ($site_log as $klog=>$vlog) {
                    if($vlog['type'] == '副运营'){
                        if(!empty($remarks)){
                            $remarks = $remarks.'
                            |
                            '.$vlog['site_name'].'店铺担任'.$vlog['type'].',副运营标签是'.$vlog['label'].'('.date('Y-m-d',$vlog['createtime']) .'-'.date('Y-m-d',$vlog['updatetime']).')';
                        }else{
                            $remarks = $vlog['site_name'].'店铺担任'.$vlog['type'].',副运营标签是'.$vlog['label'].'('.date('Y-m-d',$vlog['createtime']) .'-'.date('Y-m-d',$vlog['updatetime']).')';
                        }
                    }else{
                        if(!empty($remarks)){
                            $remarks = $remarks.'
                            |
                            '.$vlog['site_name'].'店铺担任'.$vlog['type'].'('.date('Y-m-d',$vlog['createtime']) .'-'.date('Y-m-d',$vlog['updatetime']).')';
                        }else{
                            $remarks = $vlog['site_name'].'店铺担任'.$vlog['type'].'('.date('Y-m-d',$vlog['createtime']) .'-'.date('Y-m-d',$vlog['updatetime']).')';
                        }
                    }
                    
                }
                $zadvcost = number_format($zadvcost, 3, '.', '');
                //分组
                if($system_admin['team_id'] == 1){
                    $arr['shopify_sales_day_wh'][] = [
                        'name' => $admin_name,
                        'count' => (int)$value['counts'],
                        'total' => (float)number_format($value['total'], 3, '.', ''),
                        'advcost' => $zadvcost,
                        'roi' => $zroi,
                        'profit' => $profit,
                        'remarks' => $remarks,
                    ];
                }elseif($system_admin['team_id'] == 2){
                    $arr['shopify_sales_day_nc'][] = [
                        'name' => $admin_name,
                        'count' => (int)$value['counts'],
                        'total' => (float)number_format($value['total'], 3, '.', ''),
                        'advcost' => $zadvcost,
                        'roi' => $zroi,
                        'profit' => $profit,
                        'remarks' => $remarks,
                    ];
                }elseif($system_admin['team_id'] == 3){
                    $arr['shopify_sales_day_yc'][] = [
                        'name' => $admin_name,
                        'count' => (int)$value['counts'],
                        'total' => (float)number_format($value['total'], 3, '.', ''),
                        'advcost' => $zadvcost,
                        'roi' => $zroi,
                        'profit' => $profit,
                        'remarks' => $remarks,
                    ];
                }
                //毛利
                $arr['shopify_sales_day'][] = [
                    'name' => $admin_name,
                    'count' => (int)$value['counts'],
                    'total' => (float)number_format($value['total'], 3, '.', ''),
                    'advcost' => $zadvcost,
                    'roi' => $zroi,
                    'profit' => $profit,
                    'remarks' => $remarks,
                ];
            }
        }
        if(isset($post['admin_id']) && !empty($post['admin_id'])){
            
        }else{
            //显示没业绩的运营
            if(!empty($two_admin)){
                $system_group_admin =  table('system_group_admin')
                    ->where('group_id', 5)
                    ->select()->toarray();
                foreach ($system_group_admin as $kadmin=>$vadmin) {
                    if($vadmin['admin_id'] == 51 || $vadmin['admin_id'] == 38 || $vadmin['admin_id'] == 23 ){

                    }else{
                        if (!in_array($vadmin['admin_id'], $two_admin)) {
                            $system_admin = table('system_admin')->where(['id' => $vadmin['admin_id']])->find();
                                if (!empty($system_admin)) {
                                    if($system_admin['status'] !== 1){
                                        continue;
                                    }
                                    $admin_name = $system_admin['nickname'];
                                } else {
                                    $admin_name = '';
                                }

                                $where_admin2['admin_id'] = $vadmin['admin_id'];
                                $zadvcost_z2 = table('advertising')
                                    ->field('sum(cost) as cost')
                                    ->where($adv_where)
                                    ->where('status','normal')
                                    ->where($where_admin2)
                                    ->find();
                                if(!empty($zadvcost_z2['cost'])){
                                    $zadvcost2 = $zadvcost_z2['cost'];
                                }else{
                                    $zadvcost2 = 0;
                                }
                            //分组
                            if($system_admin['team_id'] == 1){
                                $arr['shopify_sales_day_wh'][] = [
                                    'name' => $admin_name,
                                    'count' => 0,
                                    'total' => 0,
                                    'advcost' => $zadvcost2,
                                    'roi' => '',
                                    'profit' => '',
                                    'remarks' => '',
                                ];
                            }elseif($system_admin['team_id'] == 2){
                                $arr['shopify_sales_day_nc'][] = [
                                    'name' => $admin_name,
                                    'count' => 0,
                                    'total' => 0,
                                    'advcost' => $zadvcost2,
                                    'roi' => '',
                                    'profit' => '',
                                    'remarks' => '',
                                ];
                            }elseif($system_admin['team_id'] == 3){
                                $arr['shopify_sales_day_yc'][] = [
                                    'name' => $admin_name,
                                    'count' => 0,
                                    'total' => 0,
                                    'advcost' => $zadvcost2,
                                    'roi' => '',
                                    'profit' => '',
                                    'remarks' => '',
                                ];
                            }
                            $arr['shopify_sales_day'][] = [
                                'name' => $admin_name,
                                'count' => 0,
                                'total' => 0,
                                'advcost' => $zadvcost2,
                                'roi' => '',
                                'profit' => '',
                                'remarks' => '',
                            ];
                        }
                    }
                }
            }else{
                $system_group_admin =  table('system_group_admin')
                    ->where('group_id', 5)
                    ->select()->toarray();
                foreach ($system_group_admin as $kadmin=>$vadmin) {

                    $where_admin2['admin_id'] = $vadmin['admin_id'];
                    $zadvcost_z2 = table('advertising')
                        ->field('sum(cost) as cost')
                        ->where($adv_where)
                        ->where('status','normal')
                        ->where($where_admin2)
                        ->find();
                    if(!empty($zadvcost_z2['cost'])){
                        $zadvcost2 = $zadvcost_z2['cost'];
                    }else{
                        $zadvcost2 = 0;
                    }
                        $system_admin = table('system_admin')->where(['id' => $vadmin['admin_id']])->find();
                            if (!empty($system_admin)) {
                                $admin_name = $system_admin['nickname'];
                            } else {
                                $admin_name = '';
                            }
                        $arr['shopify_sales_day'][] = [
                            'name' => $admin_name,
                            'count' => 0,
                            'total' => 0,
                            'advcost' => $zadvcost2,
                            'roi' => '',
                            'profit' => '',
                            'remarks' => '',
                        ];
                }
            }
        }

        $redis->set('dashboard-personal-' . $start_time . '-' . $end_time . '-' . $post['day_changes'] . '-' . $post['admin_type'], $arr, 60*5);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $arr,
        ];
        return json($data);
    }

    /**
    * 方法详情
    * @param array params
    */
    public function dashboard_site()
    {
        $redis = new Redis();
        $site_arr = $redis->get('site_arr');
        if (!empty($site_arr)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $site_arr,
            ];
            return json($data);
        }
        $site_arr =  table('site')
            ->field("id,site_name,site_number")
            ->where(['status' => 'normal'])
            ->order('popular desc')
            ->select()->toarray();
        $redis->set('site_arr', $site_arr, 60*30);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $site_arr,
        ];
        return json($data);
    }

    /**
    * 方法详情
    * @param array params
    */
    public function dashboard_admin()
    {
        $redis = new Redis();
        $system_admin = $redis->get('system_admin');
        if (!empty($system_admin)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $system_admin,
            ];
            return json($data);
        }
        $system_admin =  table('system_admin')
            ->field("a.id,a.nickname,a.team_id")
            ->field("a.*")
            ->alias('a')
            ->join('qu_system_group_admin b', 'b.admin_id = a.id', 'left')
            ->where(['a.status' => 1])
            ->where(['b.group_id' => 5])
            ->order('a.popular desc')
            ->select()->toarray();
        foreach ($system_admin as $k=>$v) {
            switch ($v['team_id']) {
                case '1':
                    $system_admin[$k]['team_name'] = '武汉';
                    break;
                case '2':
                    $system_admin[$k]['team_name'] = '南昌';
                    break;
                case '3':
                    $system_admin[$k]['team_name'] = '银川';
                    break;
                default:
                    $system_admin[$k]['team_name'] = '未知';
            }
        }
        
        $redis->set('system_admin', $system_admin, 60*30);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $system_admin,
        ];
        return json($data);
    }
    
    
    //首页统计运营数据
    public function dashboard_shop()
    {
        $post = $this->request->post();

        if(isset($post['site_id']) && !empty($post['site_id'])){
            $where[] = ['site_id', 'in', $post['site_id']];
            $where2[] = ['a.site_id', 'in', $post['site_id']];
            $where_refund[] = ['site_id', 'in', $post['site_id']];
            $where_dispute[] = ['site_id', 'in', $post['site_id']];

            $post['site_type'] = implode(',',$post['site_id']); 
        }else{
            $post['site_type'] = 0; 
        }
        $start_time = !empty($post['start_time']) ? $post['start_time'] : strtotime(date('Y-m-d 00:00:00', time() - 15 * 3600));
        $start_time = strtotime(date('Y-m-d 00:00:00', $start_time));
        if ($post['day_changes'] == 3) {
            $start_time = strtotime(date('Y-m-1 00:00:00', $start_time));
        }
        $start_time_str = date('Y-m-d H:i:s', $start_time);
        $end_time = !empty($post['end_time']) ? $post['end_time'] : strtotime(date('Y-m-d 00:00:00', time() + 9 * 3600));
        if ($post['day_changes'] == 101) {
            $end_time = strtotime(date('Y-m-d 23:59:59', $end_time));
        } else {
            $end_time = strtotime(date('Y-m-d 00:00:00', $end_time));
        }
        $today = strtotime(date('Y-m-d 23:59:59', time()));
        if($end_time >= $today){
            return error('未生成今日报表');
        }
        $end_time_str =  date('Y-m-d H:i:s', $end_time);
        $redis = new Redis();
        $dashboards = $redis->get('dashboard-shop-' . $start_time . '-' . $end_time . '-' . $post['day_changes'] . '-' . $post['site_type']);
        if (!empty($dashboards)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $dashboards,
            ];
            return json($data);
        }
        $exchange = $redis->get('exchangerate');
        if(empty($exchange)){
            $exchange = table('exchange')
                ->where('currency','USD')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate', $exchange, 60 * 60 * 24 );
        }
        $exchange_eur = $redis->get('exchangerate_eur');
        if(empty($exchange_eur)){
            $exchange_eur = table('exchange')
                ->where('currency','EUR')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate_eur', $exchange_eur, 60 * 60 * 24 );
        }
        $where[]  = ['created_at', '>=', $start_time];
        $where[]  = ['created_at', '<=', $end_time];
        $where_total_price[] = ['financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid]];
        //已支付 + 部分退款 金额
        $where2[]  = ['a.created_at', '>=', $start_time];
        $where2[]  = ['a.created_at', '<=', $end_time];
        $where_total_price2[] = ['a.financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid]];
        $statistics = table('order')
            ->field('sum(a.total_price) as total_price,sum(a.freight) as freight,sum(a.material) as material')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->where($where2)
            ->where($where_total_price2)
            ->where(['a.status' => DicSite::$status_normal])
            ->find(); //总销售额

        $statistics1 = table('order')
            ->field('sum(a.total_price) as total_price,currency')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->where($where2)
            ->where($where_total_price2)
            ->where(['a.status' => DicSite::$status_normal])
            ->group('currency')
            ->select()->toarray(); //总销售额
        $arr['sales'] = 0;
        $arr['sales_eur'] = 0;
        $arr['sales_usd'] = 0;
        if(!empty($statistics1)){
            foreach ($statistics1 as $ks=>$vs) {
                if($vs['currency'] == 'EUR'){
                    $arr['sales_eur'] = (float)number_format((float)$vs['total_price'], 3, '.', '');
                    $sales_eur = (float)number_format((float)$arr['sales_eur'] * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                    $arr['sales'] = $arr['sales'] + $sales_eur;
                }
                if($vs['currency'] == 'USD'){
                    $arr['sales_usd'] = (float)number_format((float)$vs['total_price'], 3, '.', '');
                    $arr['sales'] = $arr['sales'] + $arr['sales_usd'];
                }
            }
        }

        $arr['sales'] = (float)number_format((float)$arr['sales'], 2, '.', '');
        $arr['platform_discount'] = (float)number_format((float)$arr['sales']*0.06, 3, '.', '');
        $arr['logistics'] = (float)number_format((float)$statistics['freight'] / (float)$exchange['proportion'], 3, '.', '');
        $arr['purchase'] = (float)number_format((float)$statistics['material'] / (float)$exchange['proportion'], 3, '.', '');

        $arr['paid'] = table('order')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->where($where2)
            ->where($where_total_price2)
            ->where(['a.status' => DicSite::$status_normal])
            ->count(); //支付订单
        $arr['authorized'] = table('order')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->where($where2)
            ->where(['a.financial_status' => 'authorized'])
            ->count();
        //退款
        $where_refund[]  = ['processed_at', '>=', $start_time];
        $where_refund[]  = ['processed_at', '<=', $end_time];
        $where_refund[]  = ['refund_status', '<=', 'success'];
        $arr['refund'] = table('order_refunds')->where($where_refund)->count(); //退款订单
        $arr['refund_money'] = number_format(table('order_refunds')->where($where_refund)->sum('amount'), 2, '.', ''); //退款金额

        //争议单
        $where_dispute[]  = ['createtime', '>=', $start_time];
        $where_dispute[]  = ['createtime', '<=', $end_time];
        $arr['dispute'] = table('order_dispute')->where($where_dispute)->count();
        //FB广告消耗金额图表

        $adv_where[]  = ['create_time', '>=', $start_time_str];
        $adv_where[]  = ['create_time', '<', $end_time_str];
        $arr['adv_cost'] = 0;

        $shopify_sales_arr = array();
        //店铺销售额
        $shopify_sales = table('order')->field('site_id,sum(total_price) as total,sum(countnum) as count,currency,sum(freight) as freight,sum(material) as material')->where($where)->where($where_total_price)->group('site_id')->order('total desc')->select()->toarray(); //总销售额
        $site_total = table('site')
            ->field('id,site_name')
            ->where('status','normal')
            ->select()->toarray();
        $site_total_new = array();
        foreach ($site_total as $k=>$v) {
            $site_total_new[$v['id']] = $v['site_name'];
        }
        if (!empty($shopify_sales)) {
            foreach ($shopify_sales as $key => $value) {
                $advplatform = table('site')->where(['id' => $value['site_id']])->find();

                $wheregroup = array();
                $wheregroup[]  = ['a.updatetime', '>=', $end_time];
                $wheregroup['a.site_id'] = $value['site_id'];
                $wheregroup['a.type'] = '主运营';
                $site_log = table('site_log')
                    ->field("b.nickname")
                    ->alias('a')
                    ->join('qu_system_admin b', 'b.id = a.admin_id', 'left')
                    ->where($wheregroup)
                    ->find();
                if(!isset($site_log['nickname']) || empty($site_log['nickname'])){
                    $site_log['nickname'] = '';
                }
                if (!empty($advplatform)) {
                    $site_name = $advplatform['site_name'];
                } else {
                    $site_name = '未知';
                }
                unset($site_total_new[$value['site_id']]);
                $zsales = (float)number_format($value['total'], 3, '.', '');
                $shopify_sales_remarks = '';
                if($value['currency'] == 'EUR'){
                    $shopify_sales_remarks = '原销售额为€'.$zsales;
                    $zsales = (float)number_format((float)$zsales * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }
                $zcount = (int)$value['count'];
                //时间段退款
                $sales_refund = table('order_refunds')
                    ->where($where_refund)
                    ->where(['site_id' => $value['site_id']])
                    ->sum('amount');
                $sales_refund = (float)number_format($sales_refund, 3, '.', '');
                //显示平台销售额
                $zadvcost_z2 = array(); 
                $zadvcost_z3 = array(); 
                $advplat_arr = table('advplat')
                    ->where('site_id',$value['site_id'])
                    ->select()->toarray();
                $zadvcost_new = 0;
                if(!empty($advplat_arr)){
                    foreach ($advplat_arr as $k0=>$v0) {
                        if($v0['adv_id'] == 1){
                            $zadvcost_z2 = table('advertising')
                                ->where($adv_where)
                                ->where('plat_account',$v0['id'])
                                ->where('status','normal')
                                ->select()->toarray();
                                if(!empty($zadvcost_z2)){
                                    foreach ($zadvcost_z2 as $k1=>$v1) {
                                        $zadvcost_new = (float)number_format((float)$zadvcost_new + (float)$v1['cost'], 3, '.', '');
                                    }
                                }
                        }else{
                            $zadvcost_z3 = table('advertising')
                                ->where($adv_where)
                                ->where('plat_account',$v0['id'])
                                ->where('status','normal')
                                ->select()->toarray();
                                if(!empty($zadvcost_z3)){
                                    foreach ($zadvcost_z3 as $k2=>$v2) {
                                        $zadvcost_new = (float)number_format((float)$zadvcost_new + (float)$v2['cost'], 3, '.', '');
                                    }
                                }
                        }
                    }
                }
                $arr['adv_cost'] = (float)number_format((float)$zadvcost_new + (float)$arr['adv_cost'], 3, '.', '');
                if ($zsales > 0.02 && $zadvcost_new > 0.02) {
                    $roi = (float)number_format((float)$zsales / (float)$zadvcost_new, 3, '.', '');
                }else{
                    $roi = 0;
                }

                $value['freight'] = (float)number_format((float)$value['freight'] / (float)$exchange['proportion'], 3, '.', '');
                $value['material'] = (float)number_format((float)$value['material'] / (float)$exchange['proportion'], 3, '.', '');
                $gross_profit = (float)number_format((float)$zsales*0.94 - (float)$value['freight'] - (float)$value['material'] - $zadvcost_new, 3, '.', '');
                $shopify_sales_arr[] = [
                    'id' => $value['site_id'],
                    'name' => $site_name,
                    'gross_profit' => $gross_profit,
                    'count' => $zcount,
                    'sales' => $zsales,
                    'refund' => $sales_refund,
                    'nickname' => $site_log['nickname'],
                    'zadvcost_new' => $zadvcost_new,
                    'roi' => $roi,
                    'remarks' => $shopify_sales_remarks,
                ];
            }
        }
        foreach ($site_total_new as $kst => $vst) {
            //时间段退款
            $sales_refund_st = table('order_refunds')
                ->where($where_refund)
                ->where(['site_id' => $kst])
                ->sum('amount');
            $sales_refund_st = (float)number_format($sales_refund_st, 3, '.', '');
            if($sales_refund_st >0.01){

                $wheregroup = array();
                $wheregroup[]  = ['a.updatetime', '>=', $end_time];
                $wheregroup['a.site_id'] = $kst;
                $wheregroup['a.type'] = '主运营';
                $site_log = table('site_log')
                    ->field("b.nickname")
                    ->alias('a')
                    ->join('qu_system_admin b', 'b.id = a.admin_id', 'left')
                    ->where($wheregroup)
                    ->find();
                if(!isset($site_log['nickname']) || empty($site_log['nickname'])){
                    $site_log['nickname'] = '';
                }
                $zadvcost_z2 = array(); 
                $zadvcost_z3 = array(); 
                $advplat_arr = table('advplat')
                    ->where('site_id',$kst)
                    ->select()->toarray();
                if(!empty($advplat_arr)){
                    foreach ($advplat_arr as $k0=>$v0) {
                        if($v0['adv_id'] == 1){
                            $zadvcost_z2 = table('advertising')
                                ->where($adv_where)
                                ->where('plat_account',$v0['id'])
                                ->where('status','normal')
                                ->select()->toarray();
                        }else{
                            $zadvcost_z3 = table('advertising')
                                ->where($adv_where)
                                ->where('plat_account',$v0['id'])
                                ->where('status','normal')
                                ->select()->toarray();
                        }
                    }
                }
                $zadvcost_new = 0;
                if(!empty($zadvcost_z2)){
                    foreach ($zadvcost_z2 as $k1=>$v1) {
                        $zadvcost_new = (float)number_format((float)$zadvcost_new + $v1['cost'], 3, '.', '');
                    }
                }
                if(!empty($zadvcost_z3)){
                    foreach ($zadvcost_z3 as $k2=>$v2) {
                        $zadvcost_new = (float)number_format((float)$zadvcost_new + $v2['cost'], 3, '.', '');
                    }
                }
                $arr['adv_cost'] = (float)number_format((float)$zadvcost_new + (float)$arr['adv_cost'], 3, '.', '');

                $gross_profit = (float)number_format((float)0 - $zadvcost_new, 3, '.', '');
                $shopify_sales_arr[] = [
                    'id' => $kst,
                    'name' => $vst,
                    'gross_profit' => $gross_profit,
                    'count' => 0,
                    'sales' => 0,
                    'refund' => $sales_refund_st,
                    'nickname' => $site_log['nickname'],
                    'zadvcost_new' => $zadvcost_new,
                    'roi' => 0,
                    'remarks' => '',
                ];
            }
        }
        //物流加成费
        $arr['gross_profit'] = (float)number_format((float)$arr['sales']*0.94 - (float)$arr['logistics'] - (float)$arr['purchase'] - (float)$arr['adv_cost'], 2, '.', '');
        $arr['roi'] = 0;
        if ($arr['adv_cost'] > 0.001 && $arr['sales'] > 0.001) {
            $arr['roi'] = number_format((float)$arr['sales'] / (float)$arr['adv_cost'], 3, '.', '');
        } //转化率ROI
        $sales_handle = '（美金$'.$arr['sales_usd'].',欧元€'.$arr['sales_eur'].'）';
        $paid_handle = '（争议单'.$arr['dispute'].',退款单'.$arr['refund'].',授权状态订单'.$arr['authorized'].'）';
        $gross_profit_handle = '（毛利'.$arr['gross_profit'].'
        =销售额'.$arr['sales'].'-物流'.$arr['logistics'].'-采购'.$arr['purchase'].'
        -广告'.$arr['adv_cost'].'-手续费(6%)'.$arr['platform_discount'].'）';
        $arr['gross_profit_handle1'] = '销售额-物流-采购-广告-手续费(6%)';
        $arr['gross_profit_handle2'] = $arr['sales'].'-'.$arr['logistics'].'-'.$arr['purchase'].'-'.$arr['adv_cost'].'-'.$arr['platform_discount'];
        $newarr = array();
        $newarr['arr'][] = $arr;
        $newarr['shopify_sales'] = $shopify_sales_arr;
        $newarr['sales_handle'] = $sales_handle;
        $newarr['paid_handle'] = $paid_handle;
        $newarr['gross_profit_handle'] = $gross_profit_handle;
        $newarr['start_time'] = $start_time;
        $newarr['end_time'] = $end_time;
        $redis->set('dashboard-shop-' . $start_time . '-' . $end_time . '-' . $post['day_changes'] . '-' . $post['site_type'], $newarr, 60*3);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $newarr,
        ];
        return json($data);
    }
}
